package com.base.starter.config;

import com.base.common.properties.CorsProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.format.FormatterRegistry;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

/**
 * @author zhou minghao
 * @date 2024/4/22
 * @description
 */
public class WebMvcConfig implements WebMvcConfigurer {

    @Bean
    public CustomCorsFilter myCorsFilter(CorsProperties corsProperties){
        CorsConfiguration config = new CorsConfiguration();
        config.setMaxAge(corsProperties.getAccessControlMaxAge());
        config.setAllowCredentials(corsProperties.getAccessControlAllowCredentials());
        config.setAllowedOriginPatterns(corsProperties.getAccessControlAllowOrigin());
        config.setAllowedHeaders(corsProperties.getAccessControlAllowHeaders());
        config.setAllowedMethods(corsProperties.getAccessControlAllowMethods());
        UrlBasedCorsConfigurationSource configSource = new UrlBasedCorsConfigurationSource();
        configSource.registerCorsConfiguration("/**", config);
        return new CustomCorsFilter(configSource);
    }

    @Override
    public void addCorsMappings(CorsRegistry registry) {
        WebMvcConfigurer.super.addCorsMappings(registry);
    }

    @Override
    public void addFormatters(FormatterRegistry formatterRegistry) {
        formatterRegistry.addConverter(new LocalDateConverter());
    }

}
